package com.tfjybj.itoo.exam.provider.controller;

import com.dmsdbj.itoo.tool.business.ItooResult;
import com.github.pagehelper.PageInfo;
import com.tfjybj.itoo.exam.entity.EvaluationPaperEntity;
import com.tfjybj.itoo.exam.model.EvaluationPaperModel;
import com.tfjybj.itoo.exam.model.QuestionNaireAllInfoModel;
import com.tfjybj.itoo.exam.model.StudentTeachClassModel;
import com.tfjybj.itoo.exam.model.TeacherCourseTeachClassModel;
import com.tfjybj.itoo.exam.provider.service.EvaluationPaperService;
import com.tfjybj.itoo.exam.provider.service.StudentTeachClassService;
import com.tfjybj.itoo.exam.provider.service.TeacherCourseTeachClassService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * TeEvaluationPaperController
 * teEvaluationPaper表
 *
 * @author 杨江涛
 * @version 2.0.0
 * @since 2.0.0 2018-12-18 18:19:48
 */
@Api(tags = {"问卷--EvaluationPaper表接口"})
@RequestMapping(value = "/EvaluationPaper")
@RestController
@Slf4j
public class EvaluationPaperController {

    @Resource
    private EvaluationPaperService evaluationPaperService;
    @Resource
    private TeacherCourseTeachClassService teacherCourseTeachClassService;
    @Resource
    private StudentTeachClassService studentTeachClassService;
//    @Resource
//    private RedissonClient redissonClient;

    //region 模板生成：基本增删改

    /**
     * 根据状态查询相应的模板
     * 王华伟--2019年5月4日09:44:00
     * @param status
     * @return
     */
    @ApiOperation(value = "根据状态查询相应的模板")
    @GetMapping(value = {"/selectTemplateByStatus/{status}"})
    public ItooResult selectTemplateByStatus(@ApiParam(value = "状态status", required = true) @PathVariable Integer status) {
        if(status == null){
            return ItooResult.build(ItooResult.FAIL, "参数不可为空");
        }
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("status",status);
        List<EvaluationPaperModel> resultList = evaluationPaperService.selectTemplateByStatus(paramMap);
        if (CollectionUtils.isEmpty(resultList)){
            return ItooResult.build(ItooResult.SUCCESS, "没有可用数据",null);
        }
        return ItooResult.build(ItooResult.SUCCESS, "查询成功",resultList);
    }

    /**
     * 根据教师ID查询出课程
     * 王华伟--2019年5月4日09:44:00
     * @param teacherId
     * @return
     */
    @ApiOperation(value = "根据教师ID查询出上课班")
    @GetMapping(value = {"/selectStudentyByTid/{teacherId}"})
    public ItooResult selectCourseyByTid(@ApiParam(value = "教师ID", required = true) @PathVariable String teacherId) {
        if(StringUtils.isEmpty(teacherId)){
            return ItooResult.build(ItooResult.FAIL, "参数不可为空");
        }
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("teacher_id",teacherId);
        List<TeacherCourseTeachClassModel> resultList = teacherCourseTeachClassService.selectStudentyByTid(paramMap);
        if (CollectionUtils.isEmpty(resultList)){
            return ItooResult.build(ItooResult.SUCCESS, "没有可用数据",null);
        }
        return ItooResult.build(ItooResult.SUCCESS, "查询成功",resultList);
    }

    /**
     * 根据上课班ID查询出对应学生
     * 王华伟--2019年5月4日09:44:00
     * @param teachclassId
     * @return
     */
    @ApiOperation(value = "根据上课班ID查询出对应学生")
    @GetMapping(value = {"/selectStudentByteachclassID/{teachclassId}"})
    public ItooResult selectStudentByteachclassID(@ApiParam(value = "上课班ID", required = true) @PathVariable String teachclassId) {
        if(StringUtils.isEmpty(teachclassId)){
            return ItooResult.build(ItooResult.FAIL, "参数不可为空");
        }
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("teach_class_id",teachclassId);
        List<StudentTeachClassModel> resultList = studentTeachClassService.selectStudentByteachclassID(paramMap);
        if (CollectionUtils.isEmpty(resultList)){
            return ItooResult.build(ItooResult.SUCCESS, "没有可用数据",null);
        }
        return ItooResult.build(ItooResult.SUCCESS, "查询成功",resultList);
    }

    /**
     * 添加
     *
     * @param model EvaluationPaperModel
     * @return 添加的结果
     * @author 杨江涛
     * @since 2.0.0 2018-12-18 18:19:48
     */
    @ApiOperation(value = "添加")
    @PostMapping(value = {"/create"})
    public ItooResult create(@RequestBody EvaluationPaperModel model) {
        EvaluationPaperEntity evaluationPaperEntity = new EvaluationPaperEntity();
        BeanUtils.copyProperties(model, evaluationPaperEntity);
        evaluationPaperService.save(evaluationPaperEntity);
        return ItooResult.build(ItooResult.SUCCESS, "添加成功");
    }

    /**
     * 删除
     *
     * @param id 主键id
     * @return ItooResult 是否删除成功          
     * @author 杨江涛
     * @since 2.0.0 2018-12-18 18:19:48
     */
    @ApiOperation(value = "根据id删除（单个）")
    @DeleteMapping(value = {"/delete/{id}"})
    public ItooResult delete(@ApiParam(value = "主键id", required = true) @PathVariable String id) {
        evaluationPaperService.removeById(id);
        return ItooResult.build(ItooResult.SUCCESS, "删除成功");
    }

    /**
     * 批量删除
     *
     * @param ids ids
     * @return ItooResult 批量删除是否成功结果
     * @author 杨江涛
     * @since 2.0.0 2018-12-18 18:19:48
     */
    @ApiOperation(value = "根据id批量删除")
    @DeleteMapping(value = {"/deleteByIds"})
    @ApiImplicitParam(name = "ids", value = "ids", dataType = "List<String>", required = true)
    public ItooResult deleteByIds(@RequestBody List<String> ids) {
        evaluationPaperService.removeByIds(ids);
        return ItooResult.build(ItooResult.SUCCESS, "批量删除成功");
    }

    /**
     * 修改
     *
     * @param model EvaluationPaperModel
     * @return 修改后的结果
     * @author 杨江涛
     * @since 2.0.0 2018-12-18 18:19:48
     */
    @ApiOperation(value = "根据id修改teEvaluationPaper")
    @PutMapping(value = {"/modify"})
    public ItooResult modify(@RequestBody EvaluationPaperModel model) {
        EvaluationPaperEntity evaluationPaperEntity = new EvaluationPaperEntity();
        BeanUtils.copyProperties(model, evaluationPaperEntity);
        evaluationPaperService.updateById(evaluationPaperEntity);
        return ItooResult.build(ItooResult.SUCCESS, "修改成功");
    }

    /**
     * 根据id查找TeEvaluationPaper
     *
     * @param id 主键id
     * @return 根据id查找的结果
     * @author 杨江涛
     * @since 2.0.0 2018-12-18 18:19:48
     */
    @ApiOperation(value = "根据id查询")
    @GetMapping(value = {"/findById/{id}"})
    public ItooResult findById(@ApiParam(value = "主键id", required = true) @PathVariable String id) {
        EvaluationPaperEntity evaluationPaperEntity = evaluationPaperService.getById(id);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", evaluationPaperEntity);
    }

    /**
     *  根据条件查询调查问卷或者评教问卷
     *  @since 2019-3-27 10:50:34
     * @param switchNumber 0/1
     * @return
     */
    @ApiOperation(value = "分页查询所有TeEvaluationPaper")
    @GetMapping(value = {"/questionnaireEnquiryq/{switchNumber}"})
    public ItooResult questionnaireEnquiryq(@PathVariable String switchNumber) {
        List<EvaluationPaperModel> evaluationPaperModels = evaluationPaperService.questionnaireEnquiryq(switchNumber);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", evaluationPaperModels);
    }
	
    //endregion

    /* **********************************以下为非模板生成的内容********************************* */

    /**
     * 查询已有答题记录的评教问卷--给前端问卷结果提供接口
     *
     * @param pageNo   页码
     * @param pageSize 每页条数
     * @return 已有答题记录的评教问卷结果集合
     * @author 杨晓慧
     * @since 2.0.0 2018年12月22日15:15:56
     */
    @ApiOperation(value = "分页查询所有《课程问卷结果》集合")
    @GetMapping(value = {"/queryCourseEvaluationPaperList/{pageNo}/{pageSize}"})
    public ItooResult queryCourseEvaluationPaperList(@ApiParam(name = "pageNo",value = "页码",required = true,example = "1")@PathVariable Integer pageNo,
                                                      @ApiParam(name = "pageSize",value = "页数",required = true,example = "10")@PathVariable Integer pageSize) {
        PageInfo<EvaluationPaperModel> teEvaluationPapers = evaluationPaperService.queryCourseEvaluationPaperList(pageNo, pageSize);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", teEvaluationPapers);
    }



    /**
     * 查询调查问卷
     * @return flag 问卷详情
     * @author 杨晓慧
     * @since 2.0.0 2018年12月17日15:54:37
     */
    @ApiOperation(value = "查询调查问卷")
    @GetMapping(value = {"findQuestionNaire/{paperId}/{courseId}/{studentId}/{schoolYearId}"})
    public ItooResult findQuestionNaire(@ApiParam(name = "paperId",value = "问卷id",required = true,example = "1072674594197884942")@PathVariable String paperId,
                                        @ApiParam(name = "courseId",value = "课程id",required = true,example = "1072674594197884942")@PathVariable String courseId,
                                        @ApiParam(name = "studentId",value = "学生id",required = true,example = "1072674594197884942")@PathVariable String studentId,
                                        @ApiParam(name = "schoolYearId",value = "学期学年id",required = true,example = "1072674594197884942")@PathVariable String schoolYearId){
        if (StringUtils.isEmpty(paperId)) {
            log.error("问卷id为空，学生id为{}",studentId);
            return ItooResult.build(ItooResult.FAIL,"问卷id为空");
        }
        if (StringUtils.isEmpty(courseId)) {
            log.error("课程id为空，学生id为{}",studentId);
            return ItooResult.build(ItooResult.FAIL,"课程id为空");
        }
        if (StringUtils.isEmpty(studentId)) {
            log.error("课程id为空，问卷id为{}",paperId);
            return ItooResult.build(ItooResult.FAIL,"学生id为空");
        }
        return evaluationPaperService.findQuestionNaire(paperId,courseId,studentId,schoolYearId);
    }
    /**
     * 无参查询所有可用的评教问卷
     * @return teEvaluationPaperModelList 问卷详情
     * @author 杨江涛
     * @since 2.0.0 2018-12-27 11:50:53
     */
    @ApiOperation(value = "无参查询所有可用的评教问卷")
    @GetMapping(value = {"findAllQuestionNaire"})
    public ItooResult findAllQuestionNaire(){
        List<EvaluationPaperModel> evaluationPaperModelList = evaluationPaperService.findAllQuestionNaire();
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", evaluationPaperModelList);
    }
    /**
     * 无参查询所有可用的调查问卷
     * @return teEvaluationPaperModelList 问卷详情
     * @author 杨江涛
     * @since 2.0.0 2018-12-27 15:57:40
     */
    @ApiOperation(value = "无参查询所有可用的调查问卷")
    @GetMapping(value = {"findAllSurveyQuestionNaire"})
    public ItooResult findAllSurveyQuestionNaire(){
        List<EvaluationPaperModel> evaluationPaperModelList = evaluationPaperService.findAllSurveyQuestionNaire();
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", evaluationPaperModelList);
    }

    /**
     * 更新调查问卷的状态
     * @param id 问卷id
     * @param  status 问卷状态
     * @return teEvaluationPaperModelList 问卷详情
     * @author 杨江涛
     * @since 2.0.0 2018-12-27 17:36:39
     */
    @ApiOperation(value = "更新调查问卷的状态")
    @PostMapping(value = {"updatePaperStatus/{id}/{status}"})
    public ItooResult updatePaperStatus(  @ApiParam( value = "id" ,required = true) @PathVariable String id,
                                          @ApiParam( value = "status" ,required = true) @PathVariable String status){
        if (StringUtils.isEmpty(id) && StringUtils.isEmpty(status)){
            return ItooResult.build(ItooResult.FAIL,"更新失败",null);
        } else {
            boolean isUpdatePaperStatus = evaluationPaperService.updatePaperStatus(id,status);
            return ItooResult.build(ItooResult.SUCCESS,"更新成功",isUpdatePaperStatus);
        }
    }

    /**
     * 添加调查问卷
     * @return teEvaluationPaperModelList 问卷详情
     * @author 杨江涛
     * @since 2.0.0 2018-12-27 17:36:39
     */
    @ApiOperation(value = "添加调查问卷")
    @PostMapping(value = "insertQuestionnaire")
    public ItooResult insertQuestionnaire(
            @RequestBody EvaluationPaperModel evaluationPaperModel
    ){
        if(StringUtils.isEmpty(evaluationPaperModel.getName())){
            return ItooResult.build(ItooResult.FAIL, "添加失败，请输入调查问卷名称", evaluationPaperModel);
        }else if(StringUtils.isEmpty(evaluationPaperModel.getCoursePropertyId())){
            return ItooResult.build(ItooResult.FAIL, "添加失败，请检查课程是否正确", evaluationPaperModel);
        }else if(evaluationPaperModel.getTeEvaluationPaperDetailModelList().size() == 0){
            return ItooResult.build(ItooResult.FAIL, "添加失败，请添加具体题型", evaluationPaperModel);
        }else {
            boolean teEval = evaluationPaperService.insertQuestionnaire(evaluationPaperModel);
            return ItooResult.build(ItooResult.SUCCESS, "添加成功", teEval);
        }
    }
    /**
     * 删除问卷
     * @return teEvaluationPaperModelList 问卷详情
     * @author 杨江涛
     * @since 2.0.0 2019-1-15 17:02:12
     */
    @ApiOperation(value = "删除问卷")
    @PostMapping(value = "deleteWholeQuestionnaire/{id}")
    public ItooResult deleteWholeQuestionnaire(@PathVariable String id){
        if (StringUtils.isEmpty(id)){
            return ItooResult.build(ItooResult.FAIL,"删除试卷失败", id);
        }else{
            boolean teEval = evaluationPaperService.deleteWholeQuestionnaire(id);
            return ItooResult.build(ItooResult.SUCCESS, "删除问卷成功", teEval);
        }
    }

    /**
     * 编辑问卷
     * @return TeEvaluationPaperDetailModel 问卷和试题实体
     * @author 杨江涛
     * @since 2.0.0 2019-1-18 16:28:10
     */
    @ApiOperation(value = "编辑问卷")
    @GetMapping(value = "editQuestionnaire/{id}")
    public ItooResult editQuestionnaire(@PathVariable String id){
        if (StringUtils.isEmpty(id)){
            return ItooResult.build(ItooResult.FAIL,"试卷查询失败", id);
        }else{
            EvaluationPaperModel evaluationPaperModel = evaluationPaperService.queryQuestionnaire(id);
            return ItooResult.build(ItooResult.SUCCESS, "问卷查询成功", evaluationPaperModel);
        }
    }
    /**
     * 更新调查问卷
     * @param evaluationPaperModel 整套问卷的实体
     * @return teEvaluationPaperModelList 问卷详情
     * @author 杨江涛
     * @since 2.0.0 2019年1月23日20:54:24
     */
    @ApiOperation(value = "更新调查问卷")
    @PostMapping(value = "updateQuestionnaire")
    public ItooResult updateQuestionnaire(
            @RequestBody EvaluationPaperModel evaluationPaperModel
    ){
        if(StringUtils.isEmpty(evaluationPaperModel.getName())){
            return ItooResult.build(ItooResult.FAIL, "问卷更新失败，请输入调查问卷名称", evaluationPaperModel);
        }else if(StringUtils.isEmpty(evaluationPaperModel.getCoursePropertyId())){
            return ItooResult.build(ItooResult.FAIL, "问卷更新失败，请检查课程是否正确", evaluationPaperModel);
        }else if(evaluationPaperModel.getTeEvaluationPaperDetailModelList().size() == 0){
            return ItooResult.build(ItooResult.FAIL, "问卷更新失败，请添加具体题型", evaluationPaperModel);
        }else {
            boolean teEval = evaluationPaperService.updateQuestionnaire(evaluationPaperModel);
            return ItooResult.build(ItooResult.SUCCESS, "问卷更新成功", teEval);
        }
    }

    /**
     * 模糊查询所有可用的问卷
     * @return teEvaluationPaperModelList 问卷详情
     * @author 杨江涛
     * @since 2.0.0 2019-1-25 10:31:58
     */
    @ApiOperation(value = "模糊查询所有可用的问卷")
    @GetMapping(value = {"aboutFindAllQuestionNaire/{name}/{type}"})
    public ItooResult aboutFindAllQuestionNaire(
            @ApiParam(value = "问卷名称name", required = true) @PathVariable String name,
            @ApiParam(value = "问卷类type", required = true) @PathVariable String type){
        List<EvaluationPaperModel> evaluationPaperModelList = evaluationPaperService.aboutFindAllQuestionNaire(name,type);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", evaluationPaperModelList);
    }


    /**
     * 查询问卷内容以及学生已答问卷记录
     * @return QuestionNaireAllInfoModel 问卷详情及答题记录
     * @author 魏恩君
     * @since 2.0.0 2019-1-25 10:31:58
     */
    @ApiOperation(value = "查询问卷内容以及学生已答问卷记录")
    @GetMapping(value = {"queryQuestionnaireResourse/{courseId}/{paperId}/{studentId}/{schoolYearId}"})
    public ItooResult queryQuestionnaireResourse(
            @ApiParam(value = "课程id", required = true) @PathVariable String courseId,
            @ApiParam(value = "问卷id", required = true) @PathVariable String paperId,
            @ApiParam(value = "学生id", required = true) @PathVariable String studentId,
            @ApiParam(value = "学年学期id", required = true) @PathVariable String schoolYearId){
        if(courseId == null || "".equals(courseId)){
            log.error("查询问卷内容失败，课程id为空");
            return ItooResult.build(ItooResult.FAIL,"查询问卷内容失败，课程id为空");
        }
        if(paperId == null || "".equals(paperId)){
            log.error("查询问卷内容失败，问卷id为空");
            return ItooResult.build(ItooResult.FAIL,"查询问卷内容失败，问卷id为空");
        }
        if(studentId == null || "".equals(studentId)){
            log.error("查询问卷内容失败，学生id为空");
            return ItooResult.build(ItooResult.FAIL,"查询问卷内容失败，学生id为空");
        }
        if(schoolYearId == null || "".equals(schoolYearId)){
            log.error("查询问卷内容失败，学年学期id为空");
            return ItooResult.build(ItooResult.FAIL,"查询问卷内容失败，学年学期id为空");
        }
        // 加redis锁，防止同一个考生刷新出多套问卷
        //RLock lock =redissonClient.getLock("questionNaire:redis:lock:" + studentId + paperId);
        try {
            //lock.lock(1, TimeUnit.MINUTES);
            QuestionNaireAllInfoModel questionnaireAllInfo = evaluationPaperService.queryQuestionnaireResourse(courseId,paperId,studentId,schoolYearId);
            return ItooResult.build(ItooResult.SUCCESS, "查询成功", questionnaireAllInfo);
        } finally {
            //lock.unlock();
        }
    }
}    
